{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Google Cloud SQL for PostgreSQL - `PostgresChatStore`\n",
    "\n",
    "> [Cloud SQL](https://cloud.google.com/sql) is a fully managed relational database service that offers high performance, seamless integration, and impressive scalability. It offers MySQL, PostgreSQL, and SQL Server database engines. Extend your database application to build AI-powered experiences leveraging Cloud SQL's LlamaIndex integrations.\n",
    "\n",
    "This notebook goes over how to use `Cloud SQL for PostgreSQL` to store chat history with `PostgresChatStore` class.\n",
    "\n",
    "Learn more about the package on [GitHub](https://github.com/googleapis/llama-index-cloud-sql-pg-python/).\n",
    "\n",
    "[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/llama-index-cloud-sql-pg-python/blob/main/samples/llama_index_chat_store.ipynb)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Before you begin\n",
    "\n",
    "To run this notebook, you will need to do the following:\n",
    "\n",
    " * [Create a Google Cloud Project](https://developers.google.com/workspace/guides/create-project)\n",
    " * [Enable the Cloud SQL Admin API.](https://console.cloud.google.com/flows/enableapi?apiid=sqladmin.googleapis.com)\n",
    " * [Create a Cloud SQL instance.](https://cloud.google.com/sql/docs/postgres/connect-instance-auth-proxy#create-instance)\n",
    " * [Create a Cloud SQL database.](https://cloud.google.com/sql/docs/postgres/create-manage-databases)\n",
    " * [Add a User to the database.](https://cloud.google.com/sql/docs/postgres/create-manage-users)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 🦙 Library Installation\n",
    "Install the integration library, `llama-index-cloud-sql-pg`, and the library for the embedding service, `llama-index-embeddings-vertex`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install --upgrade --quiet llama-index-cloud-sql-pg llama-index-llms-vertex llama-index"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Colab only:** Uncomment the following cell to restart the kernel or use the button to restart the kernel. For Vertex AI Workbench you can restart the terminal using the button on top."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# # Automatically restart kernel after installs so that your environment can access the new packages\n",
    "# import IPython\n",
    "\n",
    "# app = IPython.Application.instance()\n",
    "# app.kernel.do_shutdown(True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 🔐 Authentication\n",
    "Authenticate to Google Cloud as the IAM user logged into this notebook in order to access your Google Cloud Project.\n",
    "\n",
    "* If you are using Colab to run this notebook, use the cell below and continue.\n",
    "* If you are using Vertex AI Workbench, check out the setup instructions [here](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from google.colab import auth\n",
    "\n",
    "auth.authenticate_user()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### ☁ Set Your Google Cloud Project\n",
    "Set your Google Cloud project so that you can leverage Google Cloud resources within this notebook.\n",
    "\n",
    "If you don't know your project ID, try the following:\n",
    "\n",
    "* Run `gcloud config list`.\n",
    "* Run `gcloud projects list`.\n",
    "* See the support page: [Locate the project ID](https://support.google.com/googleapi/answer/7014113)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.\n",
    "\n",
    "PROJECT_ID = \"my-project-id\"  # @param {type:\"string\"}\n",
    "\n",
    "# Set the project id\n",
    "!gcloud config set project {PROJECT_ID}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Basic Usage"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Set Cloud SQL database values\n",
    "Find your database values, in the [Cloud SQL Instances page](https://console.cloud.google.com/sql?_ga=2.223735448.2062268965.1707700487-2088871159.1707257687)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# @title Set Your Values Here { display-mode: \"form\" }\n",
    "REGION = \"us-central1\"  # @param {type: \"string\"}\n",
    "INSTANCE = \"my-primary\"  # @param {type: \"string\"}\n",
    "DATABASE = \"my-database\"  # @param {type: \"string\"}\n",
    "TABLE_NAME = \"chat_store\"  # @param {type: \"string\"}\n",
    "USER = \"postgres\"  # @param {type: \"string\"}\n",
    "PASSWORD = \"my-password\"  # @param {type: \"string\"}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### PostgresEngine Connection Pool\n",
    "\n",
    "One of the requirements and arguments to establish Cloud SQL as a chat store is a `PostgresEngine` object. The `PostgresEngine`  configures a connection pool to your Cloud SQL database, enabling successful connections from your application and following industry best practices.\n",
    "\n",
    "To create a `PostgresEngine` using `PostgresEngine.from_instance()` you need to provide only 4 things:\n",
    "\n",
    "1. `project_id` : Project ID of the Google Cloud Project where the Cloud SQL instance is located.\n",
    "1. `region` : Region where the Cloud SQL instance is located.\n",
    "1. `instance` : The name of the Cloud SQL instance.\n",
    "1. `database` : The name of the database to connect to on the Cloud SQL instance.\n",
    "\n",
    "By default, [IAM database authentication](https://cloud.google.com/sql/docs/postgres/iam-authentication#iam-db-auth) will be used as the method of database authentication. This library uses the IAM principal belonging to the [Application Default Credentials (ADC)](https://cloud.google.com/docs/authentication/application-default-credentials) sourced from the envionment.\n",
    "\n",
    "For more informatin on IAM database authentication please see:\n",
    "\n",
    "* [Configure an instance for IAM database authentication](https://cloud.google.com/sql/docs/postgres/create-edit-iam-instances)\n",
    "* [Manage users with IAM database authentication](https://cloud.google.com/sql/docs/postgres/add-manage-iam-users)\n",
    "\n",
    "Optionally, [built-in database authentication](https://cloud.google.com/sql/docs/postgres/built-in-authentication) using a username and password to access the Cloud SQL database can also be used. Just provide the optional `user` and `password` arguments to `PostgresEngine.from_instance()`:\n",
    "\n",
    "* `user` : Database user to use for built-in database authentication and login\n",
    "* `password` : Database password to use for built-in database authentication and login.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Note:** This tutorial demonstrates the async interface. All async methods have corresponding sync methods."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index_cloud_sql_pg import PostgresEngine\n",
    "\n",
    "engine = await PostgresEngine.afrom_instance(\n",
    "    project_id=PROJECT_ID,\n",
    "    region=REGION,\n",
    "    instance=INSTANCE,\n",
    "    database=DATABASE,\n",
    "    user=USER,\n",
    "    password=PASSWORD,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize a table\n",
    "The `PostgresChatStore` class requires a database table. The `PostgresEngine` engine has a helper method `ainit_chat_store_table()` that can be used to create a table with the proper schema for you."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "await engine.ainit_chat_store_table(table_name=TABLE_NAME)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Optional Tip: 💡\n",
    "You can also specify a schema name by passing `schema_name` wherever you pass `table_name`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "SCHEMA_NAME = \"my_schema\"\n",
    "\n",
    "await engine.ainit_chat_store_table(\n",
    "    table_name=TABLE_NAME,\n",
    "    schema_name=SCHEMA_NAME,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize a default PostgresChatStore"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index_cloud_sql_pg import PostgresChatStore\n",
    "\n",
    "chat_store = await PostgresChatStore.create(\n",
    "    engine=engine,\n",
    "    table_name=TABLE_NAME,\n",
    "    # schema_name=SCHEMA_NAME\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create a ChatMemoryBuffer\n",
    "The `ChatMemoryBuffer` stores a history of recent chat messages, enabling the LLM to access relevant context from prior interactions.\n",
    "\n",
    "By passing our chat store into the `ChatMemoryBuffer`, it can automatically retrieve and update messages associated with a specific session ID or `chat_store_key`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.memory import ChatMemoryBuffer\n",
    "\n",
    "memory = ChatMemoryBuffer.from_defaults(\n",
    "    token_limit=3000,\n",
    "    chat_store=chat_store,\n",
    "    chat_store_key=\"user1\",\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create an LLM class instance\n",
    "\n",
    "You can use any of the [LLMs compatible with LlamaIndex](https://docs.llamaindex.ai/en/stable/module_guides/models/llms/modules/).\n",
    "You may need to enable Vertex AI API to use `Vertex`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.vertex import Vertex\n",
    "\n",
    "llm = Vertex(model=\"gemini-1.5-flash-002\", project=PROJECT_ID)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Use the PostgresChatStore without a storage context"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Create a Simple Chat Engine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.chat_engine import SimpleChatEngine\n",
    "\n",
    "chat_engine = SimpleChatEngine(memory=memory, llm=llm, prefix_messages=[])\n",
    "\n",
    "response = chat_engine.chat(\"Hello\")\n",
    "\n",
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Use the PostgresChatStore with a storage context"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Create a LlamaIndex `Index`\n",
    "\n",
    "An `Index` is allows us to quickly retrieve relevant context for a user query.\n",
    "They are used to build `QueryEngines` and `ChatEngines`.\n",
    "For a list of indexes that can be built in LlamaIndex, see [Index Guide](https://docs.llamaindex.ai/en/stable/module_guides/indexing/index_guide/).\n",
    "\n",
    "A `VectorStoreIndex`, can be built using the `PostgresVectorStore`. See the detailed guide on how to use the `PostgresVectorStore` to build an index [here](https://github.com/googleapis/llama-index-cloud-sql-pg-python/blob/main/samples/llama_index_vector_store.ipynb).\n",
    "\n",
    "You can also use the `PostgresDocumentStore` and `PostgresIndexStore` to persist documents and index metadata.\n",
    "These modules can be used to build other `Indexes`.\n",
    "For a detailed python notebook on this, see [LlamaIndex Doc Store Guide](https://github.com/googleapis/llama-index-cloud-sql-pg-python/blob/main/samples/llama_index_doc_store.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Create and use the Chat Engine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create an `index` here\n",
    "\n",
    "chat_engine = index.as_chat_engine(llm=llm, chat_mode=\"context\", memory=memory)  # type: ignore\n",
    "response = chat_engine.chat(\"What did the author do?\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "senseAIenv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
